import BaseEvent from '@/components/events/BaseEvent'
import { addEvent, removeEvent } from '@/plugins/dom'

export default class LongPressEvent extends BaseEvent {
  constructor() {
    super();
    this.timeOutEvent = 0;
  }

  excute({item, vueContainer}){
    this.item = item;
    this.vueContainer = vueContainer;

    this.addTouchEventListener();
  }

  addTouchEventListener(){
    let dom = this.vueContainer.$el;
    this.onTouchStart = this.onTouchStart.bind(this);
    this.onTouchMove = this.onTouchMove.bind(this);
    this.onTouchEnd = this.onTouchEnd.bind(this);
    addEvent(dom, "touchstart", this.onTouchStart);
    addEvent(dom, "touchend", this.onTouchEnd);
  }

  onTouchStart(e) {
    e.stopPropagation;
    e.preventDefault();

    this.timeOutEvent = window.setTimeout(() => {
      this.timeOutEvent = 0;
      this.emitItemClickEvent();
    }, 500);

    let dom = this.vueContainer.$el;
    addEvent(dom, "touchmove", this.onTouchMove);

    // return false;
    //单击开始计时 500代表0.5秒
    //如果longPress()需要传参得写成下面注释中的代码
    //timeOutEvent = setTimeout(function(){ longPress(url);},500);
  }
  onTouchEnd() {
    window.clearTimeout(this.timeOutEvent);

    let dom = this.vueContainer.$el;
    removeEvent(dom, "touchmove", this.onTouchMove);

    // if(this.timeOutEvent != 0){
    //   alert('单击执行代码区');
    // }
  }

  onTouchMove() {
    window.clearTimeout(this.timeOutEvent);
    this.timeOutEvent = 0;
    // alert('单击未松开直接滑动的执行代码区，默认取消任何操作');
  }

  emitItemClickEvent(){
    this.timeOutEvent = 0;
    if(window.wb){
      let url = this.item.commonAttr.url;
      window.wb.saveImage(url, () => {
        this.showToast("保存成功！！");
      }, null);
    }
    // EventBus.$emit("itemClick", {id: this.item.id, index: 0, e: null});
  }

  destroy(){
    super.destroy();

    this.timeOutEvent = 0;

    let dom = this.vueContainer.$el;
    removeEvent(dom, "touchstart", this.onTouchStart);
    removeEvent(dom, "touchmove", this.onTouchMove);
    removeEvent(dom, "touchend", this.onTouchEnd);
  }
}